package com.bey.keepgoing.webui.account;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.bey.keepgoing.model.User;
import com.bey.keepgoing.repository.AccountRepository;
import com.bey.keepgoing.service.account.AccountContext;

@Controller
@RequestMapping(value = "/register")
public class RegisterController {

	private AccountRepository accountRepository;

	private AccountContext accountContext;

	@RequestMapping(method = RequestMethod.GET)
	public String registerForm() {
		return "account/register";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String register(User user, RedirectAttributes redirectAttributes) {
		accountContext.registerUser(user);
		redirectAttributes.addFlashAttribute("username", user.getLoginName());
		return "redirect:/login";
	}

	@RequestMapping(value = "checkLoginName")
	@ResponseBody
	public String checkLoginName(@RequestParam("loginName") String loginName) {
		if (accountRepository.findUserByLoginName(loginName) == null) {
			return "true";
		} else {
			return "false";
		}
	}

	@Autowired
	public void setAccountRepository(AccountRepository accountRepository) {
		this.accountRepository = accountRepository;
	}

	@Autowired
	public void setAccountContext(AccountContext accountContext) {
		this.accountContext = accountContext;
	}

}
